package com.haizhi.crm.biz.service.impl;


import com.haizhi.crm.biz.dao.ConcernedDao;
import com.haizhi.crm.biz.model.ConcernedDo;
import com.haizhi.crm.biz.model.ConcernedQo;
import com.haizhi.crm.biz.service.ConcernService;
import com.haizhi.crm.common.constant.BizStatus;
import com.haizhi.crm.common.exception.UnexpectedStatusException;
import com.haizhi.crm.common.model.Response;
import com.haizhi.crm.common.util.CommonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * Created by yangyijun on 2018/6/24.
 */
@Service
public class ConcernServiceImpl implements ConcernService {

    @Autowired
    private ConcernedDao concernedDao;

    @Transactional(readOnly = false)
    @Override
    public Response concern(ConcernedQo concernedQo) {
        try {
            boolean concern = concernedQo.isConcern();
            Long userId = CommonUtils.getUserID();
            Long[] groupIds = concernedQo.getGroupId();
            String objectKey = concernedQo.getObjectKey();
            List<ConcernedDo> concernedDos = null;
            if (null == groupIds || groupIds.length == 0) {
                concernedDos = concernedDao.findByCompanyKeyAndUserId(objectKey, userId);
            } else {
                concernedDao.findBy(objectKey, userId, groupIds);
            }

            if (concern) {
                if (CollectionUtils.isEmpty(concernedDos)) {
                    save(userId, groupIds, objectKey);
                } else {
                    throw new UnexpectedStatusException(BizStatus.HAD_CONCERNED_ERROR);
                }
            } else {
                if (CollectionUtils.isEmpty(concernedDos)) {
                    throw new UnexpectedStatusException(BizStatus.UN_CONCERNED_ERROR);
                } else {
                    concernedDao.deleteInBatch(concernedDos);
                }
            }
            return Response.success();
        } catch (UnexpectedStatusException e) {
            throw new UnexpectedStatusException(e.getStatus(), e);
        } catch (Exception e) {
            throw new UnexpectedStatusException(BizStatus.SAVE_CONCERN_ERROR, e);
        }
    }

    private void save(Long userId, Long[] groupIds, String objectKey) {
        for (Long groupId : groupIds) {
            ConcernedDo concernedDo = new ConcernedDo();
            concernedDo.setCompanyKey(objectKey);
            concernedDo.setUserId(userId);
            concernedDo.setGroupId(groupId);
            concernedDo.setCreatedById(userId);
            concernedDo.setCreatedDt(new Date());
            concernedDo.setUpdateById(userId);
            concernedDo.setUpdatedDt(new Date());
            concernedDo.setEnabledFlag("1" );
            concernedDao.save(concernedDo);
        }
    }
}
